package com.jar.exercise.集合和数据结构.手写hashmap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangShengHao
 * @className MyArrayListMap
 * @description 手写基于ArrayList的HashMap集合
 * @date 2019/12/30 22:45
 */
public class MyArrayListMap<K, V> implements MyMap<K, V> {
	private List<Node> nodes = new ArrayList<>();
	private int size;

	@Override
	public int size() {
		return size;
	}

	@Override
	public V get(K k) {
		return getNode(k).getValue();
	}

	@Override
	public V put(K k, V v) {
		Node node = getNode(k);
		if (node != null) {
			node.setValue(v);
			return node.getValue();
		}
		nodes.add(new Node(k, v));
		size++;
		return v;
	}

	private Node getNode(K k) {
		for (Node node : nodes) {
			if (k.equals(node.getKey())) {
				return node;
			}
		}
		return null;
	}

	class Node implements Map.Entry<K, V> {
		private V v;
		private K k;

		public Node(K k, V v) {
			this.v = v;
			this.k = k;
		}

		@Override
		public K getKey() {
			return k;
		}

		@Override
		public V getValue() {
			return v;
		}

		@Override
		public V setValue(V value) {
			V oldValue = v;
			v = value;
			return oldValue;
		}
	}
}
